﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Pixysoft.Framework.Reflection;
using Pixysoft.Tools;

namespace Pixysoft.Weblications.Sango.Environment
{
    class WarStagehistoryHelper
    {
        static List<Entities.War_Stagehistory> orms = new List<Entities.War_Stagehistory>();

        static ReaderWriterLock locker = new ReaderWriterLock();

        public static void initialize()
        {
            orms = SettingHelper.GetNoebe().EntityNoebeCommand.Select<Entities.War_Stagehistory>();

            LoggerHelper.Info("initialize War_Stagehistory.count{0}", orms.Count);
        }

        public static Entities.War_Stagehistory searchHistory(long sectionSerialcode, long stageSerialcode)
        {
            locker.AcquireWriterLock(Timeout.Infinite);

            try
            {
                return unafeSearchHistory(sectionSerialcode, stageSerialcode);
            }
            finally
            {
                locker.ReleaseWriterLock();
            }
        }

        private static Entities.War_Stagehistory unafeSearchHistory(long sectionSerialcode, long stageSerialcode)
        {
            foreach (Entities.War_Stagehistory orm in orms)
            {
                if (orm.Sectionserialcode != sectionSerialcode)
                    continue;

                if (orm.Stageserialcode != stageSerialcode)
                    continue;

                return orm;
            }

            return unsafeCreateHistory(sectionSerialcode, stageSerialcode);
        }

        private static Entities.War_Stagehistory unsafeCreateHistory(long sectionSerialcode, long stageSerialcode)
        {
            Entities.War_Stagehistory orm = ReflectionManager.CreatePojo<Entities.War_Stagehistory>();
            orms.Add(orm);

            orm.Settingcode = PkHelper.SettingCode();
            orm.Stageserialcode = stageSerialcode;
            orm.Sectionserialcode = sectionSerialcode;
            orm.Attackcount = 0;
            orm.CreateDate = GlobalTimer.Instance.GetGlobalTime();
            orm.ModiDate = GlobalTimer.Instance.GetGlobalTime();

            return orm;
        }


        public static bool increateAttackHistory(long sectionSerialcode, long stageSerialcode, long stagePlaytimes)
        {
            locker.AcquireWriterLock(Timeout.Infinite);

            try
            {
                Entities.War_Stagehistory history = unafeSearchHistory(sectionSerialcode, stageSerialcode);

                history.Attackcount = history.Attackcount + 1;

                if (history.Attackcount > stagePlaytimes)
                    return false;

                return true;
            }
            finally
            {
                locker.ReleaseWriterLock();
            }
        }
    }
}
